import https from 'https';

export async function checkLiveStatus(userId) {
  const url = `https://api.live.bilibili.com/xlive/web-room/v1/index/getRoomBaseInfo?room_ids=${userId}&req_biz=video`;
  try {
    //logger.info(`请求URL: ${url}`);
    const data = await fetchJSON(url);

    if (data.code !== 0) {
      throw new Error(data.message);
    }

    const roomData = data.data.by_room_ids[userId];
    return {
      is_live: roomData.live_status === 1,
      room_url: roomData.live_url,
      room_title: roomData.title,
      room_cover: roomData.cover,
      userId: roomData.uid,
      uname: roomData.uname,
      live_time: roomData.live_time,
      live_id: roomData.live_id,
      online: roomData.online,
      attention: roomData.attention,
      tags: roomData.tags,
      area_name: roomData.area_name
    };
  } catch (error) {
    logger.error(`检查直播状态失败: ${error.message}`);
    return { is_live: false };
  }
}

function fetchJSON(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (res) => {
      let data = '';

      res.on('data', (chunk) => {
        data += chunk;
      });

      res.on('end', () => {
        try {
          const json = JSON.parse(data);
          resolve(json);
        } catch (err) {
          reject(new Error(`JSON 解析失败: ${err.message}`));
        }
      });
    }).on('error', (err) => {
      reject(new Error(`请求失败: ${err.message}`));
    });
  });
}
